package com.mars.boss.weixin.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mars.base.common.exception.AppException;
import com.mars.base.service.BaseService;
import com.mars.boss.weixin.entity.WxAgRelevancy;
import com.mars.boss.weixin.entity.WxArticle;
import com.mars.boss.weixin.entity.WxArticleGroup;
import com.mars.boss.weixin.mapper.WxAgRelevancyMapper;
import com.mars.boss.weixin.mapper.WxArticleGroupMapper;
import com.mars.boss.weixin.service.WxArticleGroupService;

@Service
public class WxArticleGroupServiceImpl extends
		BaseService<WxArticleGroup, Long> implements WxArticleGroupService {

	@Autowired
	private WxArticleGroupMapper mapper;

	@Autowired
	private WxAgRelevancyMapper agRelevancyMapper;

	@Transactional
	@Override
	public Integer insertArticleGroup(WxArticleGroup entity, Long[] articleIds) {
		// 创建图文组
		int insert = this.mapper.insert(entity);

		// 将图文加入到图文组
		if (null != articleIds) {
			List<WxAgRelevancy> list = new ArrayList<WxAgRelevancy>();
			for (int i = 0; i < articleIds.length; i++) {
				list.add(new WxAgRelevancy(entity.getId(), articleIds[i], 1));
			}
			this.addArticleList(list);
		}

		return insert;
	}

	@Override
	public int deleteByIds(String ids) throws AppException {
		int deleteByIds = super.deleteByIds(ids);

		String[] splitIds = ids.split(",");
		for (String id : splitIds) {
			this.deleteByArticleGroupId(Long.parseLong(id));
		}

		return deleteByIds;
	}

	@Override
	public Integer updateArticleGroup(WxArticleGroup entity, Long[] articleIds) {
		int update = super.update(entity);

		// 清空该多图文下的图文
		this.deleteByArticleGroupId(entity.getId());

		// 将图文加入到图文组
		if (null != articleIds) {
			List<WxAgRelevancy> list = new ArrayList<WxAgRelevancy>();
			for (int i = 0; i < articleIds.length; i++) {
				list.add(new WxAgRelevancy(entity.getId(), articleIds[i], 1));
			}
			this.addArticleList(list);
		}

		return update;
	}

	@Override
	public Integer addArticleList(List<WxAgRelevancy> list) {
		if (null != list && !list.isEmpty()) {
			return this.agRelevancyMapper.addArticleList(list);
		}
		return null;
	}

	@Override
	public List<WxArticle> getArticles(Long id) {
		return this.agRelevancyMapper.getArticles(id);
	}

	@Override
	public Integer deleteByArticleGroupId(Long id) {
		return this.agRelevancyMapper.deleteByArticleGroupId(id);
	}

	@Override
	public List<WxArticleGroup> combobox() {
		return this.mapper.combobox();
	}

	@Override
	public WxArticleGroup getArticleGroupAndArticles(Long id) {
		return this.mapper.getArticleGroupAndArticles(id);
	}

}
